<template>
  <!-- 商品列表 -->
  <div class="mall_page">
    <div class="mall_content gl_clear">
      <!-- 菜单 -->
      <ul class="mall_menu gl_fl">
        <li
          v-for="(item, index) in menuInfo"
          :key="index"
          :class="{active:menu.active === index}"
          class="mall_menu_item gl_ellipsis"
          @click="changeMenu(index)"
        >
          {{ item.name }}
        </li>
      </ul>

      <!-- 商品 -->
      <div class="mall_goods gl_clear">
        <!-- 推荐商品 -->
        <div v-if="recommendInfo.length" class="recommend gl_fr">
          <div class="goods_title gl_clear">
            <span class="gl_fl">推荐商品</span>
          </div>
          <ul class="gl_py_15">
            <li v-for="(item, index) in recommendInfo" :key="index" class="goods_item gl_mb_20" @click="jumpToGoodsDetail(item.productId, item, 'recommend')">
              <div class="goods_item_imgWrap">
                <template v-if="item.product.images[0]">
                  <img class="goods_item_img" :src="getStaticFileUrl(item.product.images[0].imageUrl)">
                </template>
              </div>
              <div class="goods_item_price">
                <span class="goods_item_yuan">￥</span>
                <span>{{ formatMoney(item.product.price) }}</span>
              </div>
              <div class="goods_item_desc">{{ item.product.name }}</div>
            </li>
          </ul>
        </div>
        <!-- 主商品 -->
        <div class="main_goods gl_clear">
          <template v-if="activeMenu && activeMenu.id">
            <div v-for="(item, index) in showGoods[activeMenu.id]" :key="index" class="gl_mb_20">
              <div class="goods_title gl_clear">
                <span class="gl_fl">{{ item.name }}</span>
                <span v-if="activeMenu.id === '_all'" class="more gl_fr" @click="onclickMore(item.id)">更多</span>
              </div>
              <ul class="minus20 gl_py_15 gl_clear">
                <li v-for="(jtem, jndex) in item.list" :key="jndex" class="goods_item mr_18 gl_mb_20 gl_fl" @click="jumpToGoodsDetail(jtem.id, jtem, 'unrecommend')">
                  <div class="goods_item_imgWrap">
                    <img class="goods_item_img" :src="getStaticFileUrl(jtem.images[0].imageUrl)">
                  </div>
                  <div class="goods_item_price">
                    <span class="goods_item_yuan">￥</span>
                    <span>{{ formatMoney(jtem.price) }}</span>
                  </div>
                  <div class="goods_item_desc">{{ jtem.name }}</div>
                </li>
                <li v-show="!item.list.length" class="no_goods">暂无商品</li>
              </ul>
            </div>
            <div v-show="!showGoods[activeMenu.id].length" class="no_goods gl_mb_20">{{ goodsListLoading ? '正在加载商品...' : '暂无商品' }}</div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  api_GET_MallProduct // 获取商品列表
} from '@/extend/api/shoppingmallswaggerApi/app.js';

export default {
  props: {
    shopInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    menuInfo: {
      type: Array,
      default() {
        return [];
      }
    },
    recommendInfo: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data () {
    return {
      menu: {
        active: 0
      },
      goodsListLoading: true,
      goodsRequest: [] // 获取到的全部商品列表
    };
  },
  computed: {
    activeMenu () {
      return this.menuInfo[this.menu.active];
    },
    menuIndexByIdMap () { // 组合menuIndexId: {menuId: index}
      const returnData = {};
      for (let i = 0; i < this.menuInfo.length; i++) {
        const item = this.menuInfo[i];
        returnData[item.id] = i;
      }
      return returnData;
    },
    // 处理页面展示商品，依赖goodsRequest，menu，recommend
    showGoods () {
      const _goodsFormat = {};
      for (let i = 0; i < this.goodsRequest.length; i++) {
        const item = this.goodsRequest[i];
        const _goupId = item.group.id;
        if (_goupId in _goodsFormat) {
          _goodsFormat[_goupId].push(item);
        } else {
          _goodsFormat[_goupId] = [item];
        }
      }

      const goodsStructure = {};
      for (let j = 0; j < this.menuInfo.length; j++) {
        const jtem = this.menuInfo[j];
        goodsStructure[jtem.id] = [];
        if (jtem.id === '_all') {
          // 如果是全部商品页，那么每个分组取前8或前10（有推荐商品取前8，没有推荐商品取前10）
          const sliceNum = this.recommendInfo.length ? 8 : 10;
          for (const k in _goodsFormat) {
            const ktem = _goodsFormat[k];
            if (ktem.length) {
              const _val = ktem[0];
              goodsStructure[jtem.id].push({
                name: _val.group.name,
                id: _val.group.id,
                sortOrder: _val.group.sortOrder,
                list: ktem.slice(0, sliceNum)
              });
            }
          }
        } else {
          goodsStructure[jtem.id].push({
            name: jtem.name,
            id: jtem.id,
            list: _goodsFormat[jtem.id] || []
          });
        }
      }

      if (goodsStructure['_all'] && goodsStructure['_all'].length) {
        goodsStructure['_all'].sort((a, b) => a.sortOrder - b.sortOrder);
      }
      return goodsStructure;
    }
  },
  watch: {
    shopInfo: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.id) {
          // 获取商品列表
          this.getGoodsList({
            StoreId: val.id,
            ProductStatusCodes: ['OnShelf'], // 销售中
            IncludeImages: true,
            IncludeGroup: true,
            IncludeStatus: true
          });
        }
      }
    }
  },
  created() {
    // query中携带active则使用query中的值
    this.menu.active = Number(this.$route.query.active) || 0;
  },
  methods: {
    // 切换菜单
    changeMenu (index) {
      this.menu.active = index;
      // 合并原有Query
      const _query = Object.assign({}, this.$route.query);
      _query.active = index;
      const _parms = this.$route.params;
      this.$router.push({
        name: 'MallHome',
        params: _parms,
        query: _query
      });
    },
    // 获取商品列表
    getGoodsList (qo) {
      this.goodsListLoading = true;
      api_GET_MallProduct(qo)
        .then(
          res => {
            this.goodsListLoading = false;
            console.log('getGoodsList - api_GET_MallProduct: ', res);
            if (res && res.items) {
              const _list = res.items || [];
              _list.sort((a, b) => {
                const _a = a.creationTime;
                const _b = b.creationTime;
                if (_a > _b) { return -1; }
                if (_a < _b) { return 1; }
                return 0;
              });
              this.goodsRequest = _list;
            }
          }
        )
        .catch(
          () => {
            this.goodsListLoading = false;
          }
        );
    },
    // 跳转至商品详情
    jumpToGoodsDetail (goodsId, data, type) {
      // 合并原有Query
      const _query = Object.assign({}, this.$route.query);
      // 根据商品的groupId 传递active
      const _active = type === 'recommend' ? data.product.group.id : data.group.id;
      _query.active = this.menuIndexByIdMap[_active];
      const _parms = this.$route.params;
      _parms['goodsId'] = goodsId;
      console.log(_parms);
      this.$router.push({
        name: 'MallDetail',
        params: _parms,
        query: _query
      });
    },
    // 点击更多按钮
    onclickMore (id) {
      const _menu = this.menuInfo;
      let _index = _menu.findIndex(item => item.id === id);
      _index = _index < 0 ? 0 : _index;
      this.menu.active = _index;
    },
    // 格式化货币格式 （分）
    formatMoney (num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          const _floatNum = strNum.slice(-2);
          if (Number(_floatNum)) {
            return strNum.slice(0, -2) + '.' + _floatNum; // 金额拼接
          } else {
            return strNum.slice(0, -2);
          }
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          const _floatNum = strNum.slice(-2);
          if (Number(_floatNum)) {
            return _mark + strNum.slice(0, -2) + '.' + _floatNum; // 金额拼接
          } else {
            return _mark + strNum.slice(0, -2);
          }
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
  .siper_item {
    height: 360px;
  }

  .mall_goods {
    padding-top: 20px;
    margin-left: 210px;
  }
  .more {
    font-size: 12px;
    font-weight: 400;
    color: #828282;
    cursor: pointer;
  }

  .minus20 {
    margin-right: -20px;
    padding-left: 5px;
  }
  .mr_18 {
    margin-right: 18px;
  }
  .recommend {
    margin-left: 25px;
  }
  .no_goods {
    color: #C0C4CC;
    line-height: 36px;
    font-size: 14px;
    text-align: center;
  }
</style>
